﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Threading;
using System.Xml.Linq;



namespace TS2000Control
{
    public partial class frmMain : Form
    {
        List<Radio> radios = new List<Radio>();
        
        TS2000ControlLibrary.Control ctrl = new TS2000ControlLibrary.Control();
        const int MHZ = 1000000;

        public frmMain()
        {
            InitializeComponent();
        }

        private void LoadConfiguration()
        {
            var radiosSection = ConfigurationManager.GetSection("RadioConfigSection") as RadioConfigSection;
            if (radiosSection != null)
            {
                foreach (Radio rad in radiosSection.Radios)
                {
                    var radio = new Radio()
                    {
                        Name = rad.Name,
                        Port = rad.Port,
                        Baud = rad.Baud,
                        Active = rad.Active
                    };

                    radios.Add(radio);
                }
            }

        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            LoadConfiguration();
            LoadVolume();
            LoadFavorites();
            LoadRepeaters();

            var activeRadio = radios.Where(x => ((Radio)x).Active == "true").SingleOrDefault();
            
            ctrl.Connect(activeRadio.Port, Convert.ToInt32(activeRadio.Baud));
            ctrl.OnFrequencyRead += ctrl_OnFrequencyRead;
            ctrl.OnModeRead += ctrl_OnModeRead;

            ctrl.RequestFrequency();
            ctrl.RequestOperatingMode();

            timer1.Tick += timer1_Tick;
            timer1.Interval = 50;
            timer1.Start();

            cboTuningStep.SelectedText = "1";
        }

        private void LoadVolume()
        {
            int v = SysAudio.SistemVolumChanger.GetVolume();
            tbVolume.Value = v;
        }

        void LoadFavorites()
        {
            lvFavorites.Items.Clear();

            var xml = XDocument.Load(@"favorites.xml");

            var query = xml.Root.Descendants("favorite");

            foreach (XElement item in query)
            {
                string id = (string)item.Attribute("id");
                string freq = (string)item.Attribute("frequency");
                string mode = (string)item.Attribute("mode");

                ListViewItem lvi = new ListViewItem(id);
                lvi.SubItems.Add(freq);
                lvi.SubItems.Add(mode);

                lvFavorites.Items.Add(lvi);
            }
        }

        void LoadRepeaters()
        {
            lvRepeaters.Items.Clear();

            var xml = XDocument.Load(@"repeaters.xml");

            var query = xml.Root.Descendants("repeater");

            foreach (XElement item in query)
            {
                string id = (string)item.Attribute("id");
                string name = (string)item.Attribute("name");
                string freq = (string)item.Attribute("frequency");
                string offset = (string)item.Attribute("offset");
                string tone = (string)item.Attribute("tone");
                string mode = (string)item.Attribute("mode");
                string loc = (string)item.Attribute("location");

                ListViewItem lvi = new ListViewItem(id);
                lvi.SubItems.Add(name);
                lvi.SubItems.Add(freq);
                lvi.SubItems.Add(offset);
                lvi.SubItems.Add(tone);
                lvi.SubItems.Add(mode);
                lvi.SubItems.Add(loc);

                lvRepeaters.Items.Add(lvi);
            }
        }

        void timer1_Tick(object sender, EventArgs e)
        {
            ctrl.RequestMeter();

            string s = ctrl.LastMeter;
            int v = 0;

            if (s != "" && Int32.TryParse(s, out v))
            {
                v = Convert.ToInt32(s);

                vuMeterLED1.Volume = v;
            }

            lblUTC.Text = "UTC: " + System.DateTime.UtcNow.ToShortTimeString();
        }

        void ctrl_OnModeRead(object source, TS2000ControlLibrary.ControlOperatingModeEventArgs e)
        {
            TS2000ControlLibrary.OperatingMode mode = e.GetInfo();

            if (mode == TS2000ControlLibrary.OperatingMode.AM)
            {
                this.PerformSafely(() => lblAM_Click(null, null)); 
            }

            if (mode == TS2000ControlLibrary.OperatingMode.LSB)
            {
                this.PerformSafely(() => lblLSB_Click(null, null));
            }

            if (mode == TS2000ControlLibrary.OperatingMode.USB)
            {
                this.PerformSafely(() => lblUSB_Click(null, null));
            }

            if (mode == TS2000ControlLibrary.OperatingMode.FM)
            {
                this.PerformSafely(() => lbFM_Click(null, null));
            }
        }

        void ctrl_OnFrequencyRead(object source, TS2000ControlLibrary.ControlEventArgs e)
        {
            try
            {
                double val = Convert.ToDouble(e.GetInfo());
                int ival = Convert.ToInt32(val * MHZ);

                this.PerformSafely(() => this.label1.Text = val.ToString("####.###.#0"));
                this.PerformSafely(() => this.tunerControl1.Value = ival);
            }
            catch
            {}

        }

        private void btnPowerOff_Click(object sender, EventArgs e)
        {
            ctrl.PowerOff();
        }

        private void lblAM_Click(object sender, EventArgs e)
        {
            lblAM.ForeColor = Color.Lime;
            lblUSB.ForeColor = Color.Gray;
            lblLSB.ForeColor = Color.Gray;
            lbFM.ForeColor = Color.Gray;
            ctrl.SetOperatingMode(TS2000ControlLibrary.OperatingMode.AM);
        }

        private void lblUSB_Click(object sender, EventArgs e)
        {
            lblAM.ForeColor = Color.Gray;
            lblUSB.ForeColor = Color.Lime;
            lblLSB.ForeColor = Color.Gray;
            lbFM.ForeColor = Color.Gray;
            ctrl.SetOperatingMode(TS2000ControlLibrary.OperatingMode.USB);
        }

        private void lblLSB_Click(object sender, EventArgs e)
        {
            lblAM.ForeColor = Color.Gray;
            lblUSB.ForeColor = Color.Gray;
            lblLSB.ForeColor = Color.Lime;
            lbFM.ForeColor = Color.Gray;
            ctrl.SetOperatingMode(TS2000ControlLibrary.OperatingMode.LSB);
        }


        private void lbFM_Click(object sender, EventArgs e)
        {
            lblAM.ForeColor = Color.Gray;
            lblUSB.ForeColor = Color.Gray;
            lblLSB.ForeColor = Color.Gray;
            lbFM.ForeColor = Color.Lime;
            ctrl.SetOperatingMode(TS2000ControlLibrary.OperatingMode.FM);
        }



        private void tunerControl1_ValueChanged(object Sender)
        {
            int val = tunerControl1.Value;

            ctrl.SetFrequency(val);

            double dval1 = val;
            double dval2 = dval1 / MHZ;

            this.PerformSafely(() => this.label1.Text = dval2.ToString("####.####0"));
            this.PerformSafely(() => this.lblBand.Text = tunerControl1.BandText);
        }

        private void cboTuningStep_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox cmb = (ComboBox)sender;
            int val = Convert.ToInt32(cmb.SelectedItem);

            tunerControl1.TuningStep = val;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (tunerControl1.IsScanning)
                tunerControl1.ScanStop();
            else
                tunerControl1.ScanStart(TS2000Control.UserControls.ScanDirection.Forward);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (tunerControl1.IsScanning)
                tunerControl1.ScanStop();
            else
                tunerControl1.ScanStart(TS2000Control.UserControls.ScanDirection.Backward);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            ctrl.SendCommand(textBox1.Text);
        }

        private void btnAddFavorite_Click(object sender, EventArgs e)
        {
            var xml = XDocument.Load(@"favorites.xml");

            var query = xml.Descendants("favorites");

            int count = query.Descendants().Count() + 1;

            string mode = "";

            if (lblUSB.ForeColor == Color.Lime) mode = "USB";
            if (lblLSB.ForeColor == Color.Lime) mode = "LSB";
            if (lblAM.ForeColor == Color.Lime) mode = "AM";
            if (lbFM.ForeColor == Color.Lime) mode = "FM";


            XElement newElement = new XElement("favorite", new XAttribute("id", count.ToString()), new XAttribute("frequency", label1.Text), new XAttribute("mode", mode));

            query.Last().Add(newElement);

            xml.Save(@"favorites.xml");

            LoadFavorites();
        }

        private void lvFavorites_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lvFavorites.SelectedItems.Count > 0)
            {
                ListViewItem item = lvFavorites.SelectedItems[0];

                string id = item.Text;
                string freq = item.SubItems[1].Text;
                string mode = item.SubItems[2].Text;

                switch (mode)
                {
                    case "USB": lblUSB_Click(null, null); break;
                    case "LSB": lblLSB_Click(null, null); break;
                    case "AM": lblAM_Click(null, null); break;
                    case "FM": lbFM_Click(null, null); break;
                }

                int v = Convert.ToInt32(Convert.ToDouble(freq) * MHZ);
                tunerControl1.Value = v;
            }


        }

        private void btnRemoveFavorite_Click(object sender, EventArgs e)
        {
            if (lvFavorites.SelectedItems.Count > 0)
            {
                ListViewItem item = lvFavorites.SelectedItems[0];

                string id = item.Text;

                var xml = XDocument.Load(@"favorites.xml");

                var query = xml.Descendants("favorites");

                var zz = query.Elements().Where(x => x.Attributes("id").SingleOrDefault().Value == id).SingleOrDefault();

                zz.Remove();

                int count = 1;
                foreach (XElement xelem in query.Descendants())
                {
                    xelem.Attribute("id").Value = count.ToString();
                    count++;
                }


                xml.Save(@"favorites.xml");

                LoadFavorites();
            }
        }

        private void lvRepeaters_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lvRepeaters.SelectedItems.Count > 0)
            {
                ListViewItem item = lvRepeaters.SelectedItems[0];

                string id = item.Text;
                string name = item.SubItems[1].Text;
                string freq = item.SubItems[2].Text;
                string offset = item.SubItems[3].Text;
                string tone = item.SubItems[4].Text;
                string mode = item.SubItems[5].Text;

                switch (mode)
                {
                    case "USB": lblUSB_Click(null, null); break;
                    case "LSB": lblLSB_Click(null, null); break;
                    case "AM": lblAM_Click(null, null); break;
                    case "FM": lbFM_Click(null, null); break;
                }

                int v = Convert.ToInt32(Convert.ToDouble(freq) * MHZ);
                tunerControl1.Value = v;

                if (tone != "")
                {
                    ctrl.SetToneFrequency(Convert.ToDouble(tone));
                    ctrl.SetTone(TS2000ControlLibrary.OnOff.On);
                }
                else
                    ctrl.SetTone(TS2000ControlLibrary.OnOff.Off);

                TS2000ControlLibrary.OffsetShift os = TS2000ControlLibrary.OffsetShift.None;
                if(offset == "+") os = TS2000ControlLibrary.OffsetShift.Plus;
                if(offset == "-") os = TS2000ControlLibrary.OffsetShift.Minus;
                ctrl.SetOffsetShift(os);
            }
        }

        private void tbVolume_Scroll(object sender, EventArgs e)
        {
            SysAudio.SistemVolumChanger.SetVolume(tbVolume.Value);
        }

        private void bandsUserControl1_BandChanged(object Sender)
        {
            int f = Convert.ToInt32(bandsUserControl1.Frequency * MHZ);
            TS2000ControlLibrary.OperatingMode mode = bandsUserControl1.Mode;

            tunerControl1.Value = f;

            switch (mode)
            {
                case TS2000ControlLibrary.OperatingMode.USB: lblUSB_Click(null, null); break;
                case TS2000ControlLibrary.OperatingMode.LSB: lblLSB_Click(null, null); break;
                case TS2000ControlLibrary.OperatingMode.AM: lblAM_Click(null, null); break;
                case TS2000ControlLibrary.OperatingMode.FM: lbFM_Click(null, null); break;
            }
            
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form f = new AboutBox1();
            f.StartPosition = FormStartPosition.CenterScreen;
            f.Show();
        }




















    }
}
